/**
 * 资源优化工具 - 适老化版本
 * 专门针对老年人使用场景的资源优化
 */

class ResourceOptimizer {
  constructor() {
    this.imageCache = new Map()
    this.fontCache = new Map()
    this.audioCache = new Map()
    this.maxCacheSize = 50 * 1024 * 1024 // 50MB
    this.currentCacheSize = 0
  }

  // 图片优化
  optimizeImage(imageUrl, options = {}) {
    const {
      width = 400,
      height = 400,
      quality = 0.8,
      format = 'webp'
    } = options

    // 检查缓存
    const cacheKey = `${imageUrl}_${width}_${height}_${quality}`
    if (this.imageCache.has(cacheKey)) {
      return this.imageCache.get(cacheKey)
    }

    // 生成优化后的图片URL
    const optimizedUrl = this.generateOptimizedImageUrl(imageUrl, {
      width,
      height,
      quality,
      format
    })

    // 缓存结果
    this.imageCache.set(cacheKey, optimizedUrl)
    this.updateCacheSize()

    return optimizedUrl
  }

  // 生成优化后的图片URL
  generateOptimizedImageUrl(originalUrl, options) {
    // 在实际应用中，这里会调用图片处理服务
    // 例如：阿里云OSS、腾讯云COS等
    const { width, height, quality, format } = options
    
    // 模拟图片优化URL生成
    if (originalUrl.includes('http')) {
      return `${originalUrl}?x-oss-process=image/resize,w_${width},h_${height}/quality,q_${Math.round(quality * 100)}/format,${format}`
    }
    
    return originalUrl
  }

  // 字体优化
  optimizeFont(fontFamily, options = {}) {
    const {
      weight = 'normal',
      style = 'normal',
      subset = 'latin'
    } = options

    const cacheKey = `${fontFamily}_${weight}_${style}_${subset}`
    if (this.fontCache.has(cacheKey)) {
      return this.fontCache.get(cacheKey)
    }

    // 生成优化后的字体URL
    const optimizedFont = this.generateOptimizedFontUrl(fontFamily, {
      weight,
      style,
      subset
    })

    this.fontCache.set(cacheKey, optimizedFont)
    this.updateCacheSize()

    return optimizedFont
  }

  // 生成优化后的字体URL
  generateOptimizedFontUrl(fontFamily, options) {
    // 在实际应用中，这里会调用字体服务
    // 例如：Google Fonts、Adobe Fonts等
    const { weight, style, subset } = options
    
    return {
      family: fontFamily,
      weight,
      style,
      subset,
      url: `https://fonts.googleapis.com/css2?family=${fontFamily}:wght@${weight}&display=swap&subset=${subset}`
    }
  }

  // 音频优化
  optimizeAudio(audioUrl, options = {}) {
    const {
      bitrate = 128,
      format = 'mp3',
      sampleRate = 44100
    } = options

    const cacheKey = `${audioUrl}_${bitrate}_${format}_${sampleRate}`
    if (this.audioCache.has(cacheKey)) {
      return this.audioCache.get(cacheKey)
    }

    // 生成优化后的音频URL
    const optimizedUrl = this.generateOptimizedAudioUrl(audioUrl, {
      bitrate,
      format,
      sampleRate
    })

    this.audioCache.set(cacheKey, optimizedUrl)
    this.updateCacheSize()

    return optimizedUrl
  }

  // 生成优化后的音频URL
  generateOptimizedAudioUrl(originalUrl, options) {
    // 在实际应用中，这里会调用音频处理服务
    const { bitrate, format, sampleRate } = options
    
    if (originalUrl.includes('http')) {
      return `${originalUrl}?bitrate=${bitrate}&format=${format}&sample_rate=${sampleRate}`
    }
    
    return originalUrl
  }

  // 预加载关键资源
  preloadCriticalResources(resources) {
    const preloadPromises = resources.map(resource => {
      return this.preloadResource(resource)
    })

    return Promise.allSettled(preloadPromises)
  }

  // 预加载单个资源
  preloadResource(resource) {
    return new Promise((resolve, reject) => {
      const { type, url, priority = 'low' } = resource

      switch (type) {
        case 'image':
          this.preloadImage(url, priority).then(resolve).catch(reject)
          break
        case 'font':
          this.preloadFont(url, priority).then(resolve).catch(reject)
          break
        case 'audio':
          this.preloadAudio(url, priority).then(resolve).catch(reject)
          break
        default:
          reject(new Error(`Unsupported resource type: ${type}`))
      }
    })
  }

  // 预加载图片
  preloadImage(url, priority = 'low') {
    return new Promise((resolve, reject) => {
      const img = new Image()
      img.onload = () => {
        console.log(`[资源优化] 图片预加载成功: ${url}`)
        resolve(url)
      }
      img.onerror = () => {
        console.warn(`[资源优化] 图片预加载失败: ${url}`)
        reject(new Error(`Failed to preload image: ${url}`))
      }
      img.src = url
    })
  }

  // 预加载字体
  preloadFont(url, priority = 'low') {
    return new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'preload'
      link.as = 'font'
      link.type = 'font/woff2'
      link.crossOrigin = 'anonymous'
      link.href = url
      
      link.onload = () => {
        console.log(`[资源优化] 字体预加载成功: ${url}`)
        resolve(url)
      }
      link.onerror = () => {
        console.warn(`[资源优化] 字体预加载失败: ${url}`)
        reject(new Error(`Failed to preload font: ${url}`))
      }
      
      document.head.appendChild(link)
    })
  }

  // 预加载音频
  preloadAudio(url, priority = 'low') {
    return new Promise((resolve, reject) => {
      const audio = new Audio()
      audio.preload = 'metadata'
      audio.oncanplaythrough = () => {
        console.log(`[资源优化] 音频预加载成功: ${url}`)
        resolve(url)
      }
      audio.onerror = () => {
        console.warn(`[资源优化] 音频预加载失败: ${url}`)
        reject(new Error(`Failed to preload audio: ${url}`))
      }
      audio.src = url
    })
  }

  // 懒加载图片
  lazyLoadImage(element, imageUrl, options = {}) {
    const {
      placeholder = '/static/placeholder.png',
      threshold = 0.1
    } = options

    // 设置占位符
    element.src = placeholder

    // 创建Intersection Observer
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 图片进入视口，开始加载
          this.loadImageWithOptimization(entry.target, imageUrl, options)
          observer.unobserve(entry.target)
        }
      })
    }, { threshold })

    observer.observe(element)
  }

  // 加载优化后的图片
  loadImageWithOptimization(element, imageUrl, options = {}) {
    const optimizedUrl = this.optimizeImage(imageUrl, options)
    
    element.onload = () => {
      console.log(`[资源优化] 图片懒加载成功: ${imageUrl}`)
    }
    
    element.onerror = () => {
      console.warn(`[资源优化] 图片懒加载失败: ${imageUrl}`)
      // 回退到原始图片
      element.src = imageUrl
    }
    
    element.src = optimizedUrl
  }

  // 更新缓存大小
  updateCacheSize() {
    // 简化的缓存大小计算
    this.currentCacheSize = this.imageCache.size * 1024 * 1024 // 假设每个图片1MB
    
    // 如果缓存过大，清理最旧的缓存
    if (this.currentCacheSize > this.maxCacheSize) {
      this.cleanupCache()
    }
  }

  // 清理缓存
  cleanupCache() {
    const maxItems = 20 // 最多保留20个缓存项
    
    // 清理图片缓存
    if (this.imageCache.size > maxItems) {
      const keys = Array.from(this.imageCache.keys())
      const keysToDelete = keys.slice(0, keys.length - maxItems)
      keysToDelete.forEach(key => this.imageCache.delete(key))
    }
    
    // 清理字体缓存
    if (this.fontCache.size > maxItems) {
      const keys = Array.from(this.fontCache.keys())
      const keysToDelete = keys.slice(0, keys.length - maxItems)
      keysToDelete.forEach(key => this.fontCache.delete(key))
    }
    
    // 清理音频缓存
    if (this.audioCache.size > maxItems) {
      const keys = Array.from(this.audioCache.keys())
      const keysToDelete = keys.slice(0, keys.length - maxItems)
      keysToDelete.forEach(key => this.audioCache.delete(key))
    }
    
    console.log('[资源优化] 缓存已清理')
  }

  // 获取缓存统计
  getCacheStats() {
    return {
      imageCache: this.imageCache.size,
      fontCache: this.fontCache.size,
      audioCache: this.audioCache.size,
      totalSize: this.currentCacheSize,
      maxSize: this.maxCacheSize
    }
  }

  // 清空所有缓存
  clearAllCache() {
    this.imageCache.clear()
    this.fontCache.clear()
    this.audioCache.clear()
    this.currentCacheSize = 0
    console.log('[资源优化] 所有缓存已清空')
  }
}

// 创建全局实例
const resourceOptimizer = new ResourceOptimizer()

export { resourceOptimizer, ResourceOptimizer }
